package kr.etcsoft.examples.binding.viewer.table;

import kr.etcsoft.examples.binding.model.Person;
import kr.etcsoft.examples.binding.model.ViewModel;
import kr.etcsoft.examples.binding.viewer.support.InlineEditingSupport;

import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.BeanProperties;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.core.databinding.observable.list.WritableList;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.databinding.viewers.ViewerSupport;
import org.eclipse.jface.databinding.viewers.ViewersObservables;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.ui.part.ViewPart;

public class EditingView extends ViewPart {
    private ViewModel viewModel = new ViewModel();
    private Table committers;
    private Label selectedCommitter;

    public EditingView() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public void createPartControl(Composite parent) {
        committers = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION);
        committers.setLinesVisible(true);

        selectedCommitter = new Label(parent, SWT.NONE);

        DataBindingContext bindingContext = new DataBindingContext();
        bindGUI(bindingContext);
    }

    protected void bindGUI(DataBindingContext bindingContext) {
        // Since we're using a JFace Viewer, we do first wrap our Table...
        TableViewer peopleViewer = new TableViewer(committers);

        TableViewerColumn column = new TableViewerColumn(peopleViewer,
                SWT.NONE);
        column.setEditingSupport(new InlineEditingSupport(peopleViewer,
                bindingContext));
        column.getColumn().setWidth(100);

        // Bind viewer to model
        ViewerSupport.bind(peopleViewer, new WritableList(viewModel
                .getPeople(), Person.class), BeanProperties.value(
                Person.class, "name"));

        // bind selectedCommitter label to the name of the current selection
        IObservableValue selection = ViewersObservables
                .observeSingleSelection(peopleViewer);
        bindingContext.bindValue(SWTObservables
                .observeText(selectedCommitter), BeansObservables
                .observeDetailValue(selection, "name", String.class));
    }

    @Override
    public void setFocus() {
        // TODO Auto-generated method stub

    }

}
